import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter_shop/common/index.dart';
import 'package:flutter_shop/model/address_bean.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AddressProvider extends ChangeNotifier {
  String addressString = "[]";
  List<AddressBean> addressList = [];

  add(AddressBean item) async {
    addressList ??= [];
    addressList.add(item);
    notifyListeners();
    save();
  }

  remove(AddressBean item) async {
    addressList ??= [];
    addressList.remove(item);
    notifyListeners();
    save();
  }

  change(AddressBean item) async {
    addressList ??= [];

    int currentIndex = 0;
    int index = -1;
    addressList.forEach((element) {
      if (item.id == element.id) {
        index = currentIndex;
      }
      currentIndex++;
    });
    if (index == -1) return;
    addressList[index] = item;
    notifyListeners();
    save();
  }

  save() async {
    addressString = json.encode(addressList);
    printLong(addressString);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('addressString', addressString);
  }

  refresh() async {
    addressList = [];
    SharedPreferences prefs = await SharedPreferences.getInstance();
    addressString = prefs.getString('addressString'); //获取持久化存储的值
    addressString ??= '';
//    print('地址信息：$addressString');
    if (addressString.isEmpty) {
      addressString =
          '[{"name":"大弟弟","phone":"18888888888","address":"太太的心里","isDefault":false},{"name":"小哥哥","phone":"13333333333","address":"妹妹的眼中","isDefault":false}]';
    }
    var temp =
        addressString == null ? [] : json.decode(addressString.toString());
    //把获得值转变成List
    List<Map> tempList = (temp as List).cast();
    tempList.forEach((element) {
      addressList.add(AddressBean.fromJson(element));
    });
    notifyListeners();
  }
}
